<template>
  <div class="flex flex-col h-auto p-2 bg-gray-200 rounded w-95/100">
    <div class="self-end mt-2 mb-4 mr-6">
      <span class="text-xl text-gray-400">清单</span>
    </div>
    <div class="flex items-center justify-between m-4">
      <a-popconfirm
        title="你确定要下单吗?"
        ok-text="Yes"
        cancel-text="No"
        @confirm="handleConfirm"
        @cancel="handleCancel"
        v-if="listing.length"
      >
        <button class="text-xs btn">confirm</button>
      </a-popconfirm>

      <span class="ml-2 text-sm font-bold">
        清单总价:
        {{ !listing.length ? "暂无" : listingPriceInfo.originalCost }}
      </span>
      <span class="text-sm font-bold">
        清单折后价:
        {{ !listing.length ? "暂无" : listingPriceInfo.realCost }}
      </span>
      <span class="text-sm font-bold">折扣: {{ !listing.length ? "暂无" : listingPriceInfo.discount }}</span>
    </div>

    <ListCard v-for="item in listing" :key="item.id" :goodInfo="item" />
  </div>
</template>

<script lang="ts" setup>
import type { GoodInfo } from "@/interface/good"
import type { AllPrice } from "@/interface/price"
import { ref, watch,computed } from "vue"
import ListCard from "@/components/ListCard.vue"
import { useGoodsStore } from "@/store/modules/goods"
import { message } from "ant-design-vue"
import { formatTimeStr, formatCurrTime } from '@/utils/fomatTime'
import { submitListing } from "@/api/listing"

const goodsStore = useGoodsStore()

const listing = computed(() => goodsStore.listing)
const listingPriceInfo = ref<AllPrice>({
  realCost: -1,
  originalCost: -1,
  discount: -1,
})

watch(
  () => goodsStore.listing,
  async (curr) => {
    const res = (await goodsStore.getListingPriceInfo(curr)) as AllPrice
    listingPriceInfo.value = res
  },
  {
    deep: true,
    immediate: true,
  }
)

const handleConfirm = async () => {
  message.success("下单成功")
  const userId = sessionStorage.getItem("uid") as string
  const date = formatCurrTime()
  const order = listing.value.map((item) => ({
    gCId: item.id,
    gCNum: item.num,
    gProvideDate: formatTimeStr(item.deliveryDate),
  }))
  const data = { userId, date, order }
  const { data: { data: res } } = await submitListing(data)
  if (res === '插入成功') {
    goodsStore.clearListing()
    message.success('提交成功')
  } else {
    message.warn('提交失败')
  }
}
const handleCancel = () => {
  message.info("下单已取消")
}
</script>
<style scoped>
.btn {
  @apply w-16 h-10 font-mono bg-purple-300 rounded transform focus:ring-4 focus:ring-purple-500 focus:ring-opacity-50 focus:outline-none hover:scale-110 hover:opacity-100 opacity-90;
  @apply transition-transform duration-200 ease-out;
}
</style>
